package impl

import (
	"context"

	"atomgit.com/openlinksaas/extension-proto-gen-go.git/extension_sms_api"
	"atomgit.com/openlinksaas/tencent-sms/config"
	"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common"
	"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/profile"
	sms "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/sms/v20210111"
)

type ApiImpl struct {
	extension_sms_api.UnimplementedExtensionSmsApiServer
	cfg *config.ServerConfig
}

func NewApiImpl(cfg *config.ServerConfig) (*ApiImpl, error) {
	return &ApiImpl{cfg: cfg}, nil
}

func (apiImpl *ApiImpl) SendRegSms(ctx context.Context, req *extension_sms_api.SendRegSmsRequest) (*extension_sms_api.SendRegSmsResponse, error) {
	cred := common.NewCredential(apiImpl.cfg.SecretId, apiImpl.cfg.SecretKey)
	err := apiImpl.sendSms(cred, apiImpl.cfg.Region, req.Phone, apiImpl.cfg.AppId, apiImpl.cfg.SignName, apiImpl.cfg.RegSms.TemplateId, []string{req.AuthCode})
	if err != nil {
		return nil, err
	}
	return &extension_sms_api.SendRegSmsResponse{}, nil
}

func (apiImpl *ApiImpl) SendResetSms(ctx context.Context, req *extension_sms_api.SendResetSmsRequest) (*extension_sms_api.SendResetSmsResponse, error) {
	cred := common.NewCredential(apiImpl.cfg.SecretId, apiImpl.cfg.SecretKey)
	err := apiImpl.sendSms(cred, apiImpl.cfg.Region, req.Phone, apiImpl.cfg.AppId, apiImpl.cfg.SignName, apiImpl.cfg.ResetSms.TemplateId, []string{req.AuthCode})
	if err != nil {
		return nil, err
	}
	return &extension_sms_api.SendResetSmsResponse{}, nil
}

func (apiImpl *ApiImpl) sendSms(cred common.CredentialIface, region, phone, appId, signName, templateId string, paramList []string) error {
	cpf := profile.NewClientProfile()
	cpf.HttpProfile.Endpoint = "sms.tencentcloudapi.com"
	c, err := sms.NewClient(cred, region, cpf)
	if err != nil {
		return err
	}
	request := sms.NewSendSmsRequest()
	request.PhoneNumberSet = common.StringPtrs([]string{phone})
	request.SmsSdkAppId = common.StringPtr(appId)
	request.SignName = common.StringPtr(signName)
	request.TemplateId = common.StringPtr(templateId)
	request.TemplateParamSet = common.StringPtrs(paramList)

	_, err = c.SendSms(request)
	return err
}
